apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: etcd-backuper
  labels:
    job: etcd-backuper
  namespace: kube-system
spec:
  # 定时任务表达式，基于kube-controller-manager的时区
  schedule: '0 18 * * *'
  startingDeadlineSeconds: 1200
  concurrencyPolicy: Forbid
  successfulJobsHistoryLimit: 1
  failedJobsHistoryLimit: 1
  suspend: false
  jobTemplate:
    spec:
      activeDeadlineSeconds: 3600
      backoffLimit: 3
      completions: 1
      parallelism: 1
      template:
        spec:
          # 必须在master节点运行
          tolerations:
          - key: node-role.kubernetes.io/master
            operator: Exists
#            value: v1      #当op=Exists可为空
            effect: NoSchedule  #可以为空，匹配所有
          affinity:
            # 所有master。也可以在其中某些master
            nodeAffinity:
              requiredDuringSchedulingIgnoredDuringExecution:
                nodeSelectorTerms:
                  - matchExpressions:
                      - key: kubernetes.io/hostname
                        operator: In
                        values:
                          - k8s-master1
                          - k8s-master2
                          - k8s-master3
          containers:
          - name: etcd-backuper
            # maintainer: zhdong
            image: synin/etcdctl:3.4.16
            imagePullPolicy: IfNotPresent
            env:
              - name: ETCDCTL_API
                value: "3"
            command:
              - sh
              - -c
              - |
                set -e
                DATE=$(date +%F)
                ENDPOINTS='127.0.0.1:2379'
                find . -name "*.db" -type f -mtime +2 -exec rm -f {} \;
                etcdctl --endpoints ${ENDPOINTS} \
                  --cert=/etc/kubernetes/pki/etcd/server.crt \
                  --key=/etc/kubernetes/pki/etcd/server.key \
                  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
                  snapshot save etcd-backup-${DATE}.db
                etcdctl --endpoints ${ENDPOINTS} \
                  --cert=/etc/kubernetes/pki/etcd/server.crt \
                  --key=/etc/kubernetes/pki/etcd/server.key \
                  --cacert=/etc/kubernetes/pki/etcd/ca.crt \
                  snapshot status etcd-backup-${DATE}.db -w table
            workingDir: /mnt
            volumeMounts:
            - mountPath: /etc/kubernetes/pki/etcd
              name: etcd-certs
            - mountPath: /mnt
              name: backup-dir
          volumes:
          - hostPath:
              path: /etc/kubernetes/pki/etcd
              type: ""
            name: etcd-certs
          - hostPath:
              # 备份文件存储在主机哪个目录
              path: {{ data_root }}/etcd-backup
              type: ""
            name: backup-dir
          hostNetwork: true
          restartPolicy: Never

